package org.easy.shiro.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName: ShiroUtil
 * @Description: Shiro工具类
 * @Author zhouzhixin
 * @Date 2021/9/27
 * @Version 1.0
 */
public class ShiroUtil {

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    /**
     * 获取shiro的连接器
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取登录用户的用户名
     */
    public static String getUser() {
        return String.valueOf(SecurityUtils.getSubject().getPrincipal());
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    /**
     * 用于判断有没有获取登录用户的信息
     */
    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    /**
     * 注销用户
     */
    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    public static String getKaptcha(String key) {
        String kaptcha = getSessionAttribute(key).toString();
        getSession().removeAttribute(key);
        return kaptcha;
    }

    /**
     * 密码加密
     */
    public static Map<String, String> encryption(String password) {
        Map<String, String> passwordMap = new HashMap<>();
        String salt = UUID.randomUUID().toString();
        String pwd = new Sha256Hash(password, salt, 1000).toBase64();
        passwordMap.put("salt", salt);
        passwordMap.put("password", pwd);
        return passwordMap;
    }

}
